package com.joyoung.sweep.utils.blue;

import java.nio.charset.StandardCharsets;

/**********************************************************\
 |                                                          |
 | XXTEA.java                                               |
 |                                                          |
 | XXTEA encryption algorithm library for Java.             |
 |                                                          |
 | Encryption Algorithm Authors:                            |
 |      David J. Wheeler                                    |
 |      Roger M. Needham                                    |
 |                                                          |
 | Code Authors: Ma Bingyao <mabingyao@gmail.com>           |
 | LastModified: Mar 10, 2015                               |
 |                                                          |
 \**********************************************************/
public class XXTea {
    private static final int DELTA = 0x9E3779B9;

    public static void main(String[] args) {
        String xxteaKey = "JYBLE_Config";
        byte[] originalData1 = LinkerUtils.hexStringWithSplit2bytes(
                "FA FB 00 00 00 40 00 01 00 16 0C 4D 45 52 43 55 52 59 5F 44 31 32 30 08 31 32 33 34 61 62 63 64 11",
                " ");
        byte[] encryptedData2 = LinkerUtils.hexString2bytes(
                "C8CE6BDA5F9965A1F6CC112AA4B1AC0C2DD98750826B1B729FA88B77346C28E4B340EAA0");
        byte[] encryptedData3 = LinkerUtils.hexStringWithSplit2bytes(
                "8C E3 06 3C 8E 3D 4C 80 40 33 E6 CA 03 15 A4 92 36 20 AB 79 B8 85 CC 83 D9 D2 88 DD 41 14 02 8E 39 " +
                        "55 A9 61 54 0A BD A4", " ");
        try {
            // 模拟客户端加解密
            byte[] encryptedData1 = XXTea.encrypt(originalData1, xxteaKey);
            System.out.println("加密后的data = " + LinkerUtils.bytes2HexStringWithSplit(encryptedData1, " "));

            byte[] decryptData1 = XXTea.decrypt(encryptedData1, xxteaKey);
            System.out.println("解密后的data = " + LinkerUtils.bytes2HexStringWithSplit(decryptData1, " "));

            byte[] decryptData2 = XXTea.decrypt(encryptedData2, xxteaKey);
            System.out.println("解密后的data2= " + LinkerUtils.bytes2HexStringWithSplit(decryptData2, " "));

            byte[] decryptData3 = XXTea.decrypt(encryptedData3, xxteaKey);
            System.out.println("解密后的data3= " + LinkerUtils.bytes2HexStringWithSplit(decryptData3, " "));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static int MX(int sum, int y, int z, int p, int e, int[] k) {
        return (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
    }

    public static final byte[] encrypt(byte[] data, byte[] key) {
        if (data.length == 0) {
            return data;
        }
        return toByteArray(
                encrypt(toIntArray(data, true), toIntArray(fixKey(key), false)), false);
    }

    public static final byte[] encrypt(String data, byte[] key) {
        return encrypt(data.getBytes(StandardCharsets.UTF_8), key);
    }

    public static final byte[] encrypt(byte[] data, String key) {
        System.out.println("encrypt data=> " + LinkerUtils.bytes2HexStringWithSplit(data, " ") + " key=> " + key);
        return encrypt(data, key.getBytes(StandardCharsets.UTF_8));
    }

    public static final byte[] encrypt(String data, String key) {
        return encrypt(data.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8));
    }

    public static final String encryptToBase64String(byte[] data, byte[] key) {
        byte[] bytes = encrypt(data, key);
        if (bytes == null) return null;
        return Base64.encode(bytes);
    }

    public static final String encryptToBase64String(String data, byte[] key) {
        byte[] bytes = encrypt(data, key);
        if (bytes == null) return null;
        return Base64.encode(bytes);
    }

    public static final String encryptToBase64String(byte[] data, String key) {
        byte[] bytes = encrypt(data, key);
        if (bytes == null) return null;
        return Base64.encode(bytes);
    }

    public static final String encryptToBase64String(String data, String key) {
        byte[] bytes = encrypt(data, key);
        if (bytes == null) return null;
        return Base64.encode(bytes);
    }

    public static final byte[] decrypt(byte[] data, byte[] key) {
        if (data.length == 0) {
            return data;
        }
        return toByteArray(
                decrypt(toIntArray(data, false), toIntArray(fixKey(key), false)), true);
    }

    public static final byte[] decrypt(byte[] data, String key) {
        return decrypt(data, key.getBytes(StandardCharsets.UTF_8));
    }

    public static final byte[] decryptBase64String(String data, byte[] key) {
        return decrypt(Base64.decode(data), key);
    }

    public static final byte[] decryptBase64String(String data, String key) {
        return decrypt(Base64.decode(data), key);
    }

    public static final String decryptToString(byte[] data, byte[] key) {
        byte[] bytes = decrypt(data, key);
        if (bytes == null) return null;
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static final String decryptToString(byte[] data, String key) {
        byte[] bytes = decrypt(data, key);
        if (bytes == null) return null;
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static final String decryptBase64StringToString(String data, byte[] key) {
        byte[] bytes = decrypt(Base64.decode(data), key);
        if (bytes == null) return null;
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static final String decryptBase64StringToString(String data, String key) {
        byte[] bytes = decrypt(Base64.decode(data), key);
        if (bytes == null) return null;
        return new String(bytes, StandardCharsets.UTF_8);
    }

    private static int[] encrypt(int[] v, int[] k) {
        int n = v.length - 1;

        if (n < 1) {
            return v;
        }
        int p, q = 6 + 52 / (n + 1);
        int z = v[n], y, sum = 0, e;

        while (q-- > 0) {
            sum = sum + DELTA;
            e = sum >>> 2 & 3;
            for (p = 0; p < n; p++) {
                y = v[p + 1];
                z = v[p] += MX(sum, y, z, p, e, k);
            }
            y = v[0];
            z = v[n] += MX(sum, y, z, p, e, k);
        }
        return v;
    }

    private static int[] decrypt(int[] v, int[] k) {
        int n = v.length - 1;

        if (n < 1) {
            return v;
        }
        int p, q = 6 + 52 / (n + 1);
        int z, y = v[0], sum = q * DELTA, e;

        while (sum != 0) {
            e = sum >>> 2 & 3;
            for (p = n; p > 0; p--) {
                z = v[p - 1];
                y = v[p] -= MX(sum, y, z, p, e, k);
            }
            z = v[n];
            y = v[0] -= MX(sum, y, z, p, e, k);
            sum = sum - DELTA;
        }
        return v;
    }

    private static byte[] fixKey(byte[] key) {
        if (key.length == 16) return key;
        byte[] fixedkey = new byte[16];
        if (key.length < 16) {
            System.arraycopy(key, 0, fixedkey, 0, key.length);
        } else {
            System.arraycopy(key, 0, fixedkey, 0, 16);
        }
        return fixedkey;
    }

    private static int[] toIntArray(byte[] data, boolean includeLength) {
        int n = (((data.length & 3) == 0)
                ? (data.length >>> 2)
                : ((data.length >>> 2) + 1));
        int[] result;

        if (includeLength) {
            result = new int[n + 1];
            result[n] = data.length;
        } else {
            result = new int[n];
        }
        n = data.length;
        for (int i = 0; i < n; ++i) {
            result[i >>> 2] |= (0x000000ff & data[i]) << ((i & 3) << 3);
        }
        return result;
    }

    private static byte[] toByteArray(int[] data, boolean includeLength) {
        int n = data.length << 2;

        if (includeLength) {
            int m = data[data.length - 1];
            n -= 4;
            if ((m < n - 3) || (m > n)) {
                return null;
            }
            n = m;
        }
        byte[] result = new byte[n];

        for (int i = 0; i < n; ++i) {
            result[i] = (byte) (data[i >>> 2] >>> ((i & 3) << 3));
        }
        return result;
    }
}
